package com.hl.sfzy.controller;

import com.hl.sfzy.utils.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {
    private  String rootPath = "/usr/upload/";

    @GetMapping("/downLoad")
    public void downLoad(String fileName, HttpServletResponse httpServletResponse) throws IOException {
        //获取文件输入流对象
        FileInputStream fis = new FileInputStream(new File(rootPath,fileName));
        //设置响应类型
        httpServletResponse.setHeader("Content-Disposition", "fileName="+ URLEncoder.encode(fileName,"UTF-8"));//预览
        //设置响应流对象
        ServletOutputStream out = httpServletResponse.getOutputStream();
        //拷贝
        IOUtils.copy(fis,out);
        //关闭资源
        out.close();
        fis.close();
    }


    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        if (file.isEmpty()){
            return R.fail("文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        //唯一性
        fileName = UUID.randomUUID().toString().replace("-","")+fileName;
        //年月
        SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
        String dirName = format.format(new Date());
        //父路径(不存在则创建)
        File dirFile = new File(rootPath + dirName);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //上传
        file.transferTo(new File(dirFile,fileName));
        //真实路径(不要d:/upload)
        String realPath = dirName + "/" + fileName;
        return R.ok(realPath);
    }
}
